const {
  getMenus,
  getMenu,
  addMenu,
  updateMenu,
  deleteMenu,
} = require("@/models/admin/menu-model");
const { arrayToTree } = require("@/utils");

/**
 * 菜单分页查询
 */
exports.page = async (req, res, next) => {
  try {
    var result = await getMenus(req.query);
    if (req.query.isTree == 1) {
      result = arrayToTree(result.rows);
    }
    res.backSuccess(result);
  } catch (error) {
    next(error);
  }
};

/**
 * 添加菜单
 */
exports.append = async (req, res, next) => {
  try {
    const bodyParams = req.body;

    // 校验菜单编码是否存在
    const code_menu = await getMenu({ code: bodyParams.code });
    if (code_menu) throw new Error("菜单已存在");

    // 查询父节点
    var parent_menu;
    var level;
    var path;
    if (bodyParams.parent_id) {
      parent_menu = await getMenu({ id: bodyParams.parent_id });
    }
    if (bodyParams.parent_id != 0 && !parent_menu)
      throw new Error("父级菜单不存在");
    // 根据父级菜单配置层级和层级路径
    level = parent_menu ? parent_menu.level + 1 : 0;
    path = parent_menu ? parent_menu.path + "/" + parent_menu.id : "0";
    bodyParams.parent_id = parent_menu ? parent_menu.id : 0;

    // 初始值
    bodyParams.type = bodyParams.type || 1;
    bodyParams.sort = bodyParams.sort || 0;

    await addMenu({ ...bodyParams, level, path });
    res.backSuccess();
  } catch (error) {
    next(error);
  }
};
/**
 * 编辑菜单
 */
exports.edit = async (req, res, next) => {
  try {
    var id = req.params.id;
    var bodyParams = req.body;

    // 判断菜单是否存在
    var base_menu = await getMenu({ id });
    if (!base_menu) throw new Error("菜单不存在");

    // 查询父节点
    var parent_menu;
    var level;
    var path;
    if (bodyParams.parent_id) {
      parent_menu = await getMenu({ id: bodyParams.parent_id });
    }
    if (bodyParams.parent_id != 0 && !parent_menu)
      throw new Error("父级菜单不存在");
    // 根据父级菜单配置层级和层级路径
    level = parent_menu ? parent_menu.level + 1 : 0;
    path = parent_menu ? parent_menu.path + "/" + parent_menu.id : "0";
    bodyParams.parent_id = parent_menu ? parent_menu.id : 0;

    // 初始值
    bodyParams.type = bodyParams.type ?? 1;
    bodyParams.sort = bodyParams.sort ?? 0;

    // 编辑数据
    const result = await updateMenu(id, { ...bodyParams, level, path });
    res.backSuccess(result);
  } catch (error) {
    next(error);
  }
};
/**
 * 删除菜单
 */
exports.remove = async (req, res, next) => {
  try {
    const id = req.params.id;

    const menu = await getMenu({ id });
    if (!menu) throw new Error("菜单不存在");
    // 判断是否还有字节点
    const child_menu = await getMenu({ parent_id: id });
    if (child_menu) throw new Error("菜单下还存在子菜单");
    const result = await deleteMenu(id);
    res.backSuccess(result);
  } catch (error) {
    next(error);
  }
};
/**
 * 菜单详情
 */
exports.detail = async (req, res, next) => {
  try {
    const id = req.params.id;
    const result = await getMenu({ id });
    res.backSuccess(result);
  } catch (error) {
    next(error);
  }
};
